<template>
  <el-dialog :title="isEdit?'编辑货权控制':'新增货权控制'"
             :visible.sync="dialogForm"
             width="1200px">
    <el-form :inline="true"
             ref="form"
             :model="form"
             :rules="rules"
             class="add-form"
             label-width="110px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="货主单位"
                        prop="cargoOwnerId">
            <el-select v-model="form.cargoOwnerId"
                       placeholder="请选择"
                       :disabled="disabled"
                       @change="selectName"
                       clearable>
              <el-option v-for="(item,index) in companyList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属仓库"
                        prop="warehouseId">
            <el-select v-model="form.warehouseId"
                       placeholder="请选择"
                       :disabled="disabled"
                       clearable>
              <el-option v-for="item in warehouseList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <br /> -->
      <h3>货权控制信息</h3>
      <hr style="margin-bottom:20px;" />
      <el-row>
        <el-col :span="8">
          <el-form-item label="控制代码"
                        prop="controlCode">
            <el-input type="text"
                      v-model="form.controlCode"
                      :disabled="disabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="控制单位"
                        prop="controlOrgName">
            <el-select v-model="form.controlOrgName"
                       placeholder="请选择"
                       :disabled="disabled"
                       clearable>
              <el-option v-for="item in userList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="控制凭证号"
                        prop="receiptsNo">
            <el-input type="text"
                      v-model="form.receiptsNo"
                      :disabled="disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="控制类型"
                        prop="controlType">
            <el-select v-model="form.controlType"
                       placeholder="请选择"
                       @change="changeType"
                       :disabled="disabled"
                       clearable>
              <el-option v-for="[key, val] in _dictControlType"
                         :key="key"
                         :label="val"
                         :value="key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="控制方式"
                        prop="controlWay">
            <el-select v-model="form.controlWay"
                       placeholder="请选择"
                       :disabled="disabled"
                       clearable>
              <el-option v-for="[key, val] in _dictControlWay"
                         :key="key"
                         :label="val"
                         :value="key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注"
                        prop="remark">
            <el-input type="textarea"
                      v-model="form.remark"
                      :disabled="disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <br /> -->
      <h3>控制量</h3>
      <hr style="margin-bottom:20px;" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="质押量(吨)"
                        prop="pledgedWeight">
            <el-input type="text"
                      v-model="form.pledgedWeight"
                      :disabled="zy_disabled"></el-input>
            <el-radio v-model="form.addOrReduce"
                      v-show="show"
                      :disabled="zy_disabled"
                      label="1">增</el-radio>
            <el-radio v-model="form.addOrReduce"
                      v-show="show"
                      :disabled="zy_disabled"
                      label="2">减</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="放货量(吨)"
                        prop="releasedWeight">
            <el-input type="text"
                      v-model="form.releasedWeight "
                      :disabled="fh_disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="show">
        <el-col :span="12">
          <el-form-item label="可用量"
                        prop="totalUseWeight">
            <el-input type="text"
                      v-model="form.totalUseWeight"
                      disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际控制量/结存量"
                        label-width="1"
                        prop="factControlWeight">
            <el-input type="text"
                      v-model="form.factControlWeight"
                      disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总质押量"
                        prop="totalReleasedWeight">
            <el-input type="text"
                      v-model="form.totalReleasedWeight"
                      disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总放货量"
                        prop="totalPledgedWeight">
            <el-input type="text"
                      v-model="form.totalPledgedWeight"
                      disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注"
                        prop="checkRemark">
            <el-input type="text"
                      :rows="1"
                      v-model="form.checkRemark"
                      width="800"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <br />
      <el-row style="margin-bottom:6px;">
        <el-col :span="6">
          <h3>账页列表(请选择控制账页)</h3>
        </el-col>
        <el-col :span="6">
          <h3 class="number">选择量(吨): {{totalBalanceWeight}} </h3>
        </el-col>
      </el-row>
      <el-table :data="form.pageList"
                border
                stripe
                show-summary
                :summary-method="getSummaries"
                max-height="550">
        <el-table-column label="序号"
                         type="index"
                         width="50"></el-table-column>
        <el-table-column prop="cargoOwnerName"
                         label="货主单位"
                         width="188"></el-table-column>
        <el-table-column prop="accountpageNo"
                         label="账页号"
                         width="120"></el-table-column>
        <el-table-column prop="accountPageType"
                         label="账页类型"
                         width="80">
          <template slot-scope="scope">
            {{scope.row.accountPageType | _filterAccountPageType}}
          </template>
        </el-table-column>
        <el-table-column prop="cargoName"
                         label="品名"
                         width="80"></el-table-column>
        <el-table-column prop="normStr"
                         label="规格"
                         width="80"></el-table-column>
        <el-table-column prop="material"
                         label="材质"
                         width="80"></el-table-column>
        <el-table-column prop="madeBy"
                         label="产地"
                         width="80"></el-table-column>
        <el-table-column prop="warehouseName"
                         label="所属仓库"
                         width="80"></el-table-column>
        <el-table-column prop="balanceWeight"
                         label="结存重量"
                         width="80"></el-table-column>
        <el-table-column prop="openedWeight"
                         label="开票重量"
                         width="80"></el-table-column>
        <el-table-column prop="outWeight"
                         label="出库重量"
                         width="80"></el-table-column>
        <el-table-column prop="balanceNum"
                         label="结存件数"
                         width="80"></el-table-column>
      </el-table>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="dialogForm = false">取 消</el-button>
      <el-button class="ml-80"
                 type="primary"
                 @click="handleSubmit(false)"
                 :loading="$store.getters.loadingBtn">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { findViceAccount } from '@/api/things/accountPageList' //账页列表
import { getWarehouseList } from '@/api/adminWarehouse/adminWarehouse' //所属仓库来源于管辖仓库
import { getAccountList } from '@/api/commerce/account' //货主单位
import { getOrgList } from '@/api/system/org' //控制单位
import { addPropertyControl } from '@/api/things/propertyControl' //新增
import { updateAudit } from '@/api/things/auditList' //编辑
import autoSearchOrg from '@/components/autocomplete/autoSearchOrg'
import autoCargo from '@/components/autocomplete/autoCargo'
import { PUBLIC_LIMIT, REG_TEXT } from '@/utils/Reg'
import { sortLength } from '@/utils/rules'
import { getLocalTime } from '@/utils/dateFormat'

export default {
  name: 'addPropertyControlForm',
  components: {
    autoSearchOrg,
    autoCargo
  },
  props: ['id'],
  data() {
    return {
      form: this.clearForm(),
      isEdit: false,
      dialogForm: false,
      disabled: false,
      zy_disabled: false,
      fh_disabled: false,
      show: false,
      condition: {}, // 查询条件
      data: [], //table数组
      rules: {
        cargoOwnerId: [
          { required: true, message: '请选择货主单位', trigger: 'blur' }
        ],
        controlCode: [
          { required: true, message: '请选择控制代码', trigger: 'blur' }
        ],
        controlOrgName: [
          { required: true, message: '请选择控制单位', trigger: 'blur' }
        ],
        receiptsNo: [
          { required: true, message: '请输入控制凭证号', trigger: 'blur' }
        ],
        controlType: [
          { required: true, message: '请选择控制类型', trigger: 'blur' }
        ],
        controlWay: [
          { required: true, message: '请选择控制方式', trigger: 'blur' }
        ]
        // pledgedWeight: [
        //   { message: '请输入质押量', trigger: 'blur' }
        // ],
        // releasedWeight: [
        //   { message: '请输入放货量', trigger: 'blur' }
        // ]
      },
      warehouseList: null,
      companyList: null,
      userList: null,
      selectType: '',
      totalBalanceWeight: 0 //选择量
    }
  },
  mounted() {
    //所属仓库的下拉菜单
    getWarehouseList().then(res => {
      this.warehouseList = res.data.aaData
    }),
      //货主单位
      getAccountList().then(res => {
        this.companyList = res.data.aaData
      })
    //控制单位
    getOrgList().then(res => {
      this.userList = res.data.aaData
    })
  },
  methods: {
    clearForm() {
      return {
        accountPageIds: '',
        cargoOwnerId: null,
        controlCode: '',
        controlOrgName: '',
        controlType: '',
        controlWay: '',
        receiptsNo: '',
        remark: '',
        addOrReduce: null,
        pledgedWeight: null,
        releasedWeight: null,
        warehouseId: null,
        weight: '',
        checkRemark: '',
        pageList: []
      }
    },
         //合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if(index === 0) {
          sums[index] = '合计'
          return;
        }
        const values = data.map(item => Number(item[column.property]))
        if (
          column.property === 'balanceWeight' ||
          column.property === 'openedWeight' ||
          column.property === 'outWeight' ||
          column.property === 'balanceNum'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index]
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    //选择货主单位，显示账页列表
    selectName(val) {
      findViceAccount({ search_EQ_cargoOwnerId: val }).then(res => {
        let data = res.data.aaData
        let arr = []
        let ids = []
        if (data.length === 0) {
          this.totalBalanceWeight = 0
          this.form.accountPageIds = ''
          this.form.pageList = []
        } else {
          data.forEach(item => {
            ids.push(item.id)
            arr.push(item.balanceWeight)
          })
          //求和
          let result = arr.reduce((num, item, index) => {
            return num + item
          })
          this.totalBalanceWeight = result //选择量(吨)
          this.form.accountPageIds = ids.join(',')
          this.form.pageList = res.data.aaData
        }
      })
    },
    changeType(val) {
      this.selectType = val
      if (val === 'FH') {
        this.zy_disabled = true
        this.fh_disabled = false
      } else {
        this.fh_disabled = true
        this.zy_disabled = false
      }
    },
    /*
     * 保存 新增或编辑
     * this.isEdit 是否编辑
     * */
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.handleToEdit() : this.handleToAdd()
        } else {
          this.$message({
            message: '请检查表单',
            type: 'error'
          })
        }
      })
    },
    // 新增
    handleToAdd() {
      addPropertyControl(this.form).then(res => {
        this.$message({ message: '新增成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    // 编辑
    handleToEdit() {
      let pageList = this.form.pageList
      let ids = []
      for (let item of pageList) {
        ids.push(item.id)
      }
      this.form.accountPageIds = ids.join(',')
      updateAudit(this.id, this.form).then(res => {
        this.$message({ message: '编辑成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    dialogForm(val) {
      if (!val) {
        this.$refs.form.resetFields()
        this.isEdit = false
        this.form = this.clearForm()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.box {
  border: 2px solid #eee;
  margin: 20px 0;
}
.box .title,
.box .rule {
  background: #eee;
  height: 50px;
  line-height: 50px;
  padding-left: 10px;
}
.block {
  margin: 20px 0;
}
.number {
  color: red;
}
</style>
